package models

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type GroupApplyExtendModel interface {
	Count(ctx context.Context, groupId int64) (int64, error)
	FindList(ctx context.Context, groupId, offset, limit, status int64) ([]*GroupApply, error)
}

func NewGroupApplyExtendModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) GroupApplyExtendModel {
	return &defaultGroupApplyModel{
		CachedConn: sqlc.NewConn(conn, c, opts...),
		table:      "`group_apply`",
	}
}

func (m *defaultGroupApplyModel) Count(ctx context.Context, groupId int64) (int64, error) {
	var count int64
	query := fmt.Sprintf("select count(*) from %s where `group_id` = ? and status = 0", m.table)
	err := m.QueryRowNoCacheCtx(ctx, &count, query, groupId)
	return count, err
}

func (m *defaultGroupApplyModel) FindList(ctx context.Context, groupId, offset, limit, status int64) ([]*GroupApply, error) {
	list := make([]*GroupApply, 0)
	query := fmt.Sprintf("select %s from %s where `group_id` = ? and status = ? and id > ? offset ? order by `id` desc ", groupApplyRows, m.table)
	err := m.QueryRowsNoCacheCtx(ctx, &list, query, groupId, status, limit, offset)
	return list, err
}
